<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formPersonnelBasicRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormPersonnelBasic()" @reset="resetFormPersonnelBasic">
        <el-form-item label="姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.xmFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="性别码">
          <el-input
            class="filter-item"
            v-model="formFilter.xbmFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formPersonnelBasicTable"
      class="page-table"
      :data="formPersonnelBasicTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formPersonnelBasicTableWidgetCurrentPage - 1) * formPersonnelBasicTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formPersonnelBasicTableWidget.onSortChange"
      @refresh="formPersonnelBasicTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddPersonnelBasicClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportPersonnelBasicClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportPersonnelBasicClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" fixed="left" :index="formPersonnelBasicTableWidget.getTableIndex" :width="80" />
      <vxe-column title="姓名" field="xm" />
      <vxe-column title="英文姓名" field="ywxm" />
      <vxe-column title="性别码" field="xbm" />
      <vxe-column title="出生日期" field="csrq">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.csrq, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="出生地码" field="csdm" />
      <vxe-column title="籍贯" field="jg" />
      <vxe-column title="户口类别码" field="hklbm" />
      <vxe-column title="户口所在地行政区划码" field="hkszdxzqhm" />
      <vxe-column title="户口所在地详细地址" field="hkszdxxdz" />
      <vxe-column title="当前住址行政区划码" field="dqzzxzqhm" />
      <vxe-column title="当前住址详细地址" field="dqzzxxdz" />
      <vxe-column title="当前住址邮政编码" field="dqzzyzbm" />
      <vxe-column title="民族码" field="mzm" />
      <vxe-column title="国籍/地区码" field="gjdqm" />
      <vxe-column title="身份证件类型码" field="sfzjlxm" />
      <vxe-column title="身份证件号" field="sfzjh" />
      <vxe-column title="婚姻状况码（中小学不用填写）" field="hyzkm" />
      <vxe-column title="港澳台侨外码" field="gatqwm" />
      <vxe-column title="信仰宗教码" field="xyzjm" />
      <vxe-column title="血型码" field="xxm" />
      <vxe-column title="照片">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.zp, {
                id: scope.row.id,
                fieldName: 'zp',
                asImage: false
              })
            "
            type="text"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="是否独生子女" field="sfdszn" />
      <vxe-column title="联系电话" field="lxdh" />
      <vxe-column title="宅电" field="zd" />
      <vxe-column title="更新时间" field="updateTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.updateTime, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditPersonnelBasicClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeletePersonnelBasicClick(scope.row)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="formPersonnelBasicTableWidgetTotalCount"
            :current-page="formPersonnelBasicTableWidgetCurrentPage"
            :page-size="formPersonnelBasicTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formPersonnelBasicTableWidget.onCurrentPageChange"
            @size-change="formPersonnelBasicTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formPersonnelBasic',
};
</script>

<script setup lang="ts">
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { PersonnelBasicData } from '@/api/generated/personnelBasicController';
import { PersonnelBasicController } from '@/api/generated';
import FormEditPersonnelBasic from '@/pages/personnelBasic/formEditPersonnelBasic.vue';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 姓名
  xmFilter: undefined,
  // 性别码
  xbmFilter: undefined,
});
const formFilterCopy = reactive({
  // 姓名
  xmFilter: undefined,
  // 性别码
  xbmFilter: undefined,
});
const instance = getCurrentInstance();

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormPersonnelBasic();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormPersonnelBasicTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    personnelBasicDtoFilter: {
      xm: formFilter.xmFilter,
      xbm: formFilter.xbmFilter,
    }
  };
  return new Promise((resolve, reject) => {
    PersonnelBasicController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormPersonnelBasicTableVerify = () => {
  formFilterCopy.xmFilter = formFilter.xmFilter;
  formFilterCopy.xbmFilter = formFilter.xbmFilter;
  return true;
};
/**
 * 新建
 */
const onAddPersonnelBasicClick = (row?: PersonnelBasicData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditPersonnelBasic, { area: ['1100px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      formPersonnelBasicTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditPersonnelBasicClick = (row?: PersonnelBasicData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditPersonnelBasic, { area: ['1100px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      formPersonnelBasicTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportPersonnelBasicClick = (row?: PersonnelBasicData) => {
  let params: ANY_OBJECT = {
  };

  PersonnelBasicController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportPersonnelBasicClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  PersonnelBasicController.import(params).then(res => {
    ElMessage.success('导入成功');
    formPersonnelBasicTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeletePersonnelBasicClick = (row?: PersonnelBasicData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    PersonnelBasicController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formPersonnelBasicTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formPersonnelBasicTableOptions: TableOptions<PersonnelBasicData> = {
  loadTableData: loadFormPersonnelBasicTableWidgetData,
  verifyTableParameter: loadFormPersonnelBasicTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formPersonnelBasicTable = ref();
const formPersonnelBasicTableWidget = useTable(formPersonnelBasicTableOptions);
const {
  dataList: formPersonnelBasicTableWidgetDataList,
  currentPage: formPersonnelBasicTableWidgetCurrentPage,
  pageSize: formPersonnelBasicTableWidgetPageSize,
  totalCount: formPersonnelBasicTableWidgetTotalCount,
} = formPersonnelBasicTableWidget;
const refreshFormPersonnelBasic = () => {
  // 刷新段落
  formPersonnelBasicTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormPersonnelBasic = () => {
  formFilter.xmFilter = undefined;
  formFilterCopy.xmFilter = undefined;
  formFilter.xbmFilter = undefined;
  formFilterCopy.xbmFilter = undefined;
  refreshFormPersonnelBasic();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormPersonnelBasic();
};
const formInit = () => {
  refreshFormPersonnelBasic();
};

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>